package com.timmy.smarttest.ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.inuker.bluetooth.library.search.SearchResult;
import com.timmy.smarttest.R;
import com.timmy.smarttest.adapter.ConnectsAdapter;
import com.timmy.smarttest.adapter.ResultsAdapter;
import com.timmy.smarttest.presenter.MainActivityPresenter;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    @BindView(R.id.listview_results)
    ListView mListviewResults;
    @BindView(R.id.listview_connect)
    ListView mListviewConnect;
    @BindView(R.id.tv_ble_state)
    TextView mTvBleState;
    @BindView(R.id.tv_present)
    TextView mTvPresent;
    @BindView(R.id.radioGroup)
    RadioGroup mRadioGroup;

    private int OPEN_REQUEST_CODE = 821;
    private MainActivityPresenter mPresenter;
    private ProgressDialog mProgressDialog;
    private ResultsAdapter mResultsAdapter;
    private ConnectsAdapter mConnectsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        mPresenter = new MainActivityPresenter(this);
        // 检测蓝牙是否开启
        boolean bluetoothOpened = mPresenter.mBleUtil.isBluetoothOpened();

        if (!bluetoothOpened) {
            // 申请打开蓝牙
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, OPEN_REQUEST_CODE);
        }

        initView();
        initListener();
    }

    private void initView() {
        // 初始化各种View
        mResultsAdapter = new ResultsAdapter(this);
        mListviewResults.setAdapter(mResultsAdapter);

        // 初始化各种View
        mConnectsAdapter = new ConnectsAdapter(this);
        mListviewConnect.setAdapter(mConnectsAdapter);
    }

    private void initListener() {
        mListviewResults.setOnItemClickListener(mResultsListener);
        mListviewConnect.setOnItemClickListener(mConnectsListener);

        mRadioGroup.setOnCheckedChangeListener(mylistener);
    }

    private void scanBleDevice() {
        mPresenter.registerNotifyListener();
        mPresenter.scanBleDevice();
    }

    // 连接成功
    public void onConnectSucc() {
        mTvBleState.setText("蓝牙连接成功");
        hideProgressDialog();
    }

    // 更新adapter
    public void upData(List<SearchResult> mResults, List<SearchResult> mConnectList) {
        mResultsAdapter.setData(mResults);
        mConnectsAdapter.setData(mConnectList);
    }

    // 连接失败
    public void onConnectFaild() {
        mTvBleState.setText("蓝牙未连接");
        hideProgressDialog();
    }

    private void showToast(String text) {
        Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
    }

    public void getDevice() {
        hideProgressDialog();
    }

    @OnClick({R.id.btn_start_test, R.id.btn_scan, R.id.btn_disconnet, R.id.btn_pause_test})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_start_test:

                boolean bleState = mPresenter.getBleState();
                if (bleState) {
                    startTest();
                } else {
                    showToast("蓝牙未连接");
                }
                break;
            case R.id.btn_scan:
                showProgressDialog("扫描设备", "正在扫描...");
                scanBleDevice();
                break;
            case R.id.btn_disconnet:
                mTvPresent.setText("当前已测试:");
                mPresenter.disConnect();
                break;
            case R.id.btn_pause_test:
                // 暂停当前测试
                mPresenter.sendPauseData(checkId);
                break;
        }
    }

    // 开始测试
    private void startTest() {
        mPresenter.sendData(checkId);
        String trim = mTvPresent.getText().toString().trim();

        mTvPresent.setText(trim + " " + checkText);
    }

    private void showProgressDialog(String title, String message) {
        if (mProgressDialog == null) {
            mProgressDialog = ProgressDialog.show(MainActivity.this, title, message, false);
        } else if (mProgressDialog.isShowing()) {
            mProgressDialog.setTitle(title);
            mProgressDialog.setMessage(message);
        }
        mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }


    // ========================== 监听点击事件
    AdapterView.OnItemClickListener mResultsListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            // 判断设备是否有在连接,有的话 先断开连接
            boolean bleState = mPresenter.getBleState();

            if (bleState) {
                showToast("蓝牙正在连接,请先断开蓝牙连接");
            } else {
                showToast("蓝牙未连接");
                showProgressDialog("连接设备", "正在连接...");
                SearchResult item = (SearchResult) mResultsAdapter.getItem(position);
                // 点击开始连接设备
                mPresenter.connectDevice(item);
            }
        }
    };

    AdapterView.OnItemClickListener mConnectsListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // 移除已经连接的设备, 添加到搜索列表中
            SearchResult item = (SearchResult) mConnectsAdapter.getItem(position);
            mPresenter.mConnectList.remove(item);
            mResultsAdapter.addData(item);
            mConnectsAdapter.removeData(item);
        }
    };

    private int checkId = 0;
    private String checkText = "";

    private RadioGroup.OnCheckedChangeListener mylistener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            checkId = proofTestValue(checkedId);
        }
    };

    private int proofTestValue(int checkedId) {
        int id = 0;
        switch (checkedId) {
            case R.id.radio_1:
                id = 1;
                checkText = "LED灯";
                break;
            case R.id.radio_2:
                checkText = "马达";
                id = 2;
                break;
            case R.id.radio_3:
                checkText = "心率";
                id = 3;
                break;
            case R.id.radio_4:
                checkText = "温湿度";
                id = 4;
                break;
            case R.id.radio_5:
                checkText = "紫外线";
                id = 5;
                break;
            case R.id.radio_6:
                checkText = "VOC";
                id = 6;
                break;
            case R.id.radio_7:
                checkText = "陀螺仪";
                id = 7;
                break;
        }
        return id;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OPEN_REQUEST_CODE) {
            // 打开蓝牙了
            if (resultCode == Activity.RESULT_OK) {
                // 打开了蓝牙了
                showToast("蓝牙已打开");
            } else if (resultCode == Activity.RESULT_CANCELED) {
                showToast("权限被拒绝了");
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.disConnect();
    }
}
